package me.cabbit.digitone.support;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;


/**
 * Compact class to read strings from a file. This should help with
 * internationalization. The general format of the file must be:
 * 
 * <code>
 * # comment
 * STRING_IDENTIFIER = Your string here
 * </code>
 * 
 * where you can put as many string identifiers as you want. The file
 * is read and the strings loaded into a hash map. Strings can be later
 * referenced by their identifier using the get() method in this class
 * 
 * @author Arkaid
 *
 */
public final class Strings {
	
	//------------------------------------------------------------------//
	//--------------------------- properties ---------------------------//
	//------------------------------------------------------------------//

	/** Hashmap to store loaded strings */
	private HashMap<String, String> strings;
	
	//------------------------------------------------------------------//
	//----------------------------- methods ----------------------------//
	//------------------------------------------------------------------//
	
	/**
	 * Constructor. Loads the strings file
	 * 
	 * @param filename Strings file
	 * @throws FileNotFoundException thrown if file is not found
	 */
	public Strings(String filename) throws FileNotFoundException 
	{
		//create hashmap
		this.strings = new HashMap<String, String>();
				
		//load strings from file
		BufferedReader br = new BufferedReader(new FileReader(filename));
		String line;

		try 
		{
			while ((line = br.readLine()) != null) 
			{
				//skip comments and empty lines
				if (line.length() < 1 || line.charAt(0) == '#')
					continue;

				//split at "="
				String[] entry = line.split("=");
				
				//ignore erroneous entries
				if (entry.length != 2)
					continue;
				
				//remove trailing spaces and add to the hash
				this.strings.put(entry[0].trim(), entry[1].trim());
			}
			
			br.close();
			
		} 
		catch (IOException e) 
		{
			//TODO: Handle this exception
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Retreive a string by its id
	 * 
	 * @param id unique string identifier
	 * @return the requested string
	 */
	public String get(String id)  
	{
		if (!this.strings.containsKey(id))
			return id;
		
		return this.strings.get(id);
	}

}
